home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3409 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  53 lines

  1. Path: newshub.cts.com!RIP
  2. From: ripr@cts.com (William Rinehart)
  3. Newsgroups: comp.lang.c
  4. Subject: Help using qsort to sort pointers to a structure
  5. Date: Sun, 28 Jan 96 16:39:21 GMT
  6. Organization: CTSNET
  7. Message-ID: <4eg8rp$2oo_001@news2.cts.com>
  8. NNTP-Posting-Host: ripr.cts.com
  9.  
  10. I'm trying to use qsort to sort the "names" elements in the structure called "data".  
  11. The code below compiles with no errors or warnings, but GPFs (segmentation fault on a
  12. UNIX box) when it is run.  Apparently the fault is in the strcmp call.  I don't see 
  13. what's wrong with it.  Can anyone help?
  14.  
  15. Thanks!
  16.  
  17. #include <stdio.h> 
  18. #include <stdlib.h>  
  19. #include <string.h>
  20.  
  21. struct alpha {
  22.     char names[20];
  23. }; 
  24.  
  25. struct alpha data[4]=
  26.     { {"bbb"}, {"aaa"}, {"ddd"}, {"ccc"} };
  27.  
  28. int compname(const void *arg1, const void *arg2);
  29.  
  30. int
  31. main(void)
  32. {                   
  33.  
  34.     int i;
  35.           
  36.     for (i=0; i < 4; i++)  /* print pre-sort list */
  37.         printf("%s\n",data[i].names); 
  38.         
  39. qsort((void *)data, (size_t)4, sizeof(struct alpha *), compname);
  40.  
  41.      for (i=0; i < 4; i++)  /* print sorted list */
  42.         printf("%s\n",i, data[i].names);           
  43.     return(0);
  44. }
  45.  
  46. int
  47. compname(const void *arg1, const void *arg2)
  48. {   
  49.     /* cast arg1 and arg2 as pointers to pointers, then derefence
  50.         so that strcmp gets "regular" pointer as arguments */
  51.        return (strcmp((*(struct alpha**)arg1)->names, (*(struct alpha**)arg2)->names));
  52. }
  53.